package com.bjpowernode.boss.mvc.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.boss.constants.KeyConst;
import com.bjpowernode.boss.enums.ajax.Code;
import com.bjpowernode.boss.mvc.model.result.AjaxResult;
import com.bjpowernode.boss.utils.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

/**
 * jwt 拦截器
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 预检请求 , 直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 获取请求头数据
        String authorization = request.getHeader("Authorization");
        String operatorId = request.getHeader("operatorId");
        // 判断请求头数据是否存在
        if (StrUtil.isNotBlank(authorization) && StrUtil.isNotBlank(operatorId) && authorization.startsWith("Bearer")) {
            // 截取获得jwt
            String jwt = authorization.substring(7);
            // 从redis中获取存储的jwt 和 operatorId
            String redisJsonToken = redisUtil.getValue(KeyConst.OPERATOR_LOGIN + operatorId);
            // 判断存储的值是否为空
            if (StrUtil.isNotBlank(redisJsonToken)) {
                // 不为空 ,  解析json 获取里面的 jwt
                JSONObject object = JSONUtil.parseObj(redisJsonToken);
                String saveRedisJwt = object.getStr("jwt");
                // 判断是否为空 并进行置比
                if (StrUtil.isNotBlank(saveRedisJwt) && saveRedisJwt.equals(jwt)) {
                    // 验证成功 , jwt有效
                    return true;
                }
            }
        }

        // jwt无效
        // 无效 , 返回jwt无效的部分
        AjaxResult fail = AjaxResult.fail(Code.OPERATOR_LOGIN_JWT_INVALID);
        // 将 json对象 封装为 jsonstring数据 响应浏览器
        String loginInvValidJson = JSONUtil.toJsonStr(fail);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(loginInvValidJson);
        out.flush();
        out.close();

        return false;
    }
}
